package com.sda.huoshui.util

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.text.TextUtils
import android.util.Base64
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.blankj.utilcode.util.AppUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.google.gson.Gson
import com.makeramen.roundedimageview.RoundedImageView
import com.sda.huoshui.MyApp
import com.sda.huoshui.R
import com.sda.huoshui.base.BaseM
import java.text.DecimalFormat
import java.util.*
import java.util.regex.Pattern
import kotlin.collections.ArrayList


class CommonTools {

    companion object {

        fun toastShort(showStr:String){
            Toast.makeText(MyApp.context, showStr, Toast.LENGTH_SHORT).show()
        }

        //判断字符串是否为null或长度是否为0；
        fun isEmpty(str: String): Boolean {
            return TextUtils.isEmpty(str) || str.equals("null", ignoreCase = true)
        }

        /**
         * 是否是手机号
         */
        fun isMobileNumber(mobile: String): Boolean {
            if (mobile.length != 11) return false // "^((\\d{7,8})|(0\\d{2,3}-\\d{7,8})|(1[34578]\\d{9}))$"
            val p = Pattern.compile("^((1[3|5|6|7|8|9][0-9])|(14[5|7])|(17[0|1|6|7|8]))\\d{8}$")
            val m = p.matcher(mobile)
            return m.matches()
        }

        /**
         * 是否是金额
         */
        fun isMoney(mobile: String): Boolean {
            val p = Pattern.compile("^(([1-9]{1}\\\\d*)|([0]{1}))(\\\\.(\\\\d){0,2})?\$")
            val m = p.matcher(mobile)
            return m.matches()
        }


        /**
         * 判断微信是否可用
         *
         * @param context
         * @return
         */
        fun isWeixinAvilible(context: Context): Boolean {
            val packageManager = context.packageManager // 获取packagemanager
            val pinfo = packageManager.getInstalledPackages(0) // 获取所有已安装程序的包信息
            if (pinfo != null) {
                for (i in pinfo.indices) {
                    val pn = pinfo[i].packageName
                    if (pn == "com.tencent.mm") {
                        return true
                    }
                }
            }

            return false
        }

        /**
         * 检测是否安装支付宝
         * @param context
         * @return
         */
        public fun isAliPayInstalled(context: Context): Boolean {
            val uri = Uri.parse("alipays://platformapi/startApp")
            val intent = Intent(Intent.ACTION_VIEW, uri)
            val componentName = intent.resolveActivity(context.packageManager)
            return componentName != null;
        }


        /**
         * 检查手机上是否安装了指定的软件
         *
         * @param context
         * @param packageName：应用包名
         * @return
         */
        fun isAvilible(context: Context, packageName: String): Boolean { //获取packagemanager
            val packageManager = context.packageManager //获取所有已安装程序的包信息
            val packageInfos = packageManager.getInstalledPackages(0) //用于存储所有已安装程序的包名
            val packageNames = ArrayList<String>() //从pinfo中将包名字逐一取出，压入pName list中
            if (packageInfos != null) {
                for (i in packageInfos.indices) {
                    val packName = packageInfos[i].packageName
                    packageNames.add(packName)
                }
            } //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
            return packageNames.contains(packageName)
        }

        /**
         * 解析服务器返回数据，不同状态码不同操作
         */
        fun parsingReturnData(string: String, parsingReturnListener: OnParsingReturnListener) {
            var bean: BaseM = Gson().fromJson(string, BaseM::class.java)
            when (bean.code) {
                "1" -> {
                    parsingReturnListener.onParsingSuccess()
                }

                else -> {
                    if (bean.msg!!.toString().isNotEmpty()) {
                        if (bean.msg!!.toString().contains("无效页面")){
                            Toast.makeText(MyApp.context, "没有更多了", Toast.LENGTH_SHORT).show()
                        }else{
                            Toast.makeText(MyApp.context, bean.msg.toString(), Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }
        }

        fun getHeardsMap(): Map<String, String> {
            val heardsMap = HashMap<String, String>()
            heardsMap["source"] = "1"
//            heardsMap["Authorization"] = "JWT " + Constans.access!!
            heardsMap["version"] = AppUtils.getAppVersionName()
//            heardsMap["jpushId"] = JPushInterface.getRegistrationID(MyApp.context)
            return heardsMap
        }

        /**
         * 将请求参数包裹上params
         *
         * @param paramsMap
         * @return
         */
        fun getBodyMapForParams(paramsMap: Map<String, Any>): Map<String, Map<String, Any>> {
            val bodyMap = HashMap<String, Map<String, Any>>()
            bodyMap["params"] = paramsMap
            return bodyMap
        }

        /**
         * 将请求参数包裹上params（带分页）
         *
         * @param paramsMap
         * @return
         */
        fun getBodyMapForParamsAndPage(
            paramsMap: Map<String, Any>,
            pageNo: Int
        ): Map<String, Map<String, Any>> {
            val bodyMap = HashMap<String, Map<String, Any>>()
            val mapPage = HashMap<String, Any>()
            mapPage["pageSize"] = 20
            mapPage["pageNo"] = pageNo
            if (paramsMap.isNotEmpty()) {
                bodyMap["params"] = paramsMap
            }
            bodyMap["page"] = mapPage
            return bodyMap
        }

        fun getBodyMapForPage(params: Any, pageNo: Int): Map<String, Any> {
            val bodyMap = HashMap<String, Any>()
            val mapPage = HashMap<String, Any>()
            mapPage["pageSize"] = 20
            mapPage["pageNo"] = pageNo
            bodyMap["params"] = params
            bodyMap["page"] = mapPage
            return bodyMap
        }

        fun stringtoBitmap(string: String): Bitmap? { //将字符串转换成Bitmap类型
            var bitmap: Bitmap? = null
            try {
                val bitmapArray: ByteArray = Base64.decode(string, Base64.DEFAULT)
                bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.size)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return bitmap
        }

        /**
         * 分转元（保留两位有效数字）
         * @param amount
         * @return
         */
        fun centToYuan(amount: Int): String {
            val df = DecimalFormat("######0.00")
            val d = amount / 100
            return df.format(d).toString()
        }

        /**
         * 元转分
         * @param amount
         * @return
         */
        fun yuanToCent(amount: String): Int {
            val df = DecimalFormat("######0")
            val d = java.lang.Double.parseDouble(amount) * 100
            return df.format(d).toInt()
        }

        fun showGlideRoundedImage(
            context: Context,
            url: String,
            image: RoundedImageView,
            errorResoure: Int = R.mipmap.icon_no_pic
        ) {

            val options = RequestOptions()
//                .placeholder(errorResoure)    //加载成功之前占位图
                .error(errorResoure)    //加载错误之后的错误图
                .centerCrop()
//                .skipMemoryCache(false)    //使用内存缓存
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)    //只缓存最终的图片

            Glide.with(context).load(url).apply(options).into(image)
        }

        fun showGlideImage(
            context: Context,
            url: String?,
            image: ImageView,
            errorResoure: Int = R.mipmap.icon_no_pic
        ) {

            val options = RequestOptions()
//                .placeholder(errorResoure)    //加载成功之前占位图
                .error(errorResoure)    //加载错误之后的错误图
//                .fitCenter().skipMemoryCache(false)    //使用内存缓存
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)    //只缓存最终的图片

            Glide.with(context).load(url?:"").apply(options).into(image)
        }

        fun getEmptyView(
            context: Context,
            resId: Int = R.mipmap.icon_no_data,
            remark: String = "暂时还没有任务呀~"
        ): View {
            val view = LayoutInflater.from(context).inflate(R.layout.layout_empty_view, null)
            view.findViewById<ImageView>(R.id.ivEmptyPic).setImageResource(resId)
            view.findViewById<TextView>(R.id.tvText).setText(remark)
            return view
        }
    }

    interface OnParsingReturnListener {
        fun onParsingSuccess()
    }

}
